// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------


import {Utils} from 'sequelize';

/**
 * @parms model 当前表的模型实例
 * @options {object} 查询参数
 */
const genSqlString = function (model, options) {
  return (function (options) {
    const tableNames = {};
    tableNames[this.getTableName(options)] = true;
    options = Utils.cloneDeep(options);
    options = Object.assign({}, options, {
      hooks: true,
      rejectOnEmpty: true,
      type: 'SELECT',
      model: this,
      tableNames: Object.keys(tableNames)
    });
    options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes);

    if (options.include) {
      options.hasJoin = true;

      this._validateIncludedElements(options, tableNames);

      if (
        options.attributes
        && !options.raw
        && this.primaryKeyAttribute
        && !options.attributes.includes(this.primaryKeyAttribute)
        && (!options.group || !options.hasSingleAssociation || options.hasMultiAssociation)
      ) {
        options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
      }
    }

    if (!options.attributes) {
      options.attributes = Object.keys(this.rawAttributes);
      options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes);
    }

    this.options.whereCollection = options.where || null;

    Utils.mapFinderOptions(options, this);

    options = this._paranoidClause(this, options);

    return this.queryInterface.queryGenerator.selectQuery(this.getTableName(options), options, this);

  }).bind(model)(options);
};

export default {
  genSqlString
}
